package com.open.capacity.task.service.impl;

import com.github.pagehelper.PageInfo;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.SysTask;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.CodeEnum;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.redis.util.RedisUtil;
import com.open.capacity.task.dao.TaskDao;
import com.open.capacity.task.model.*;
import com.open.capacity.task.service.TaskService;
import com.open.capacity.task.utils.CodeGenerator;
import com.open.capacity.task.utils.Commons;
import com.open.capacity.task.utils.GetDate;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskDao taskDao;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Integer findTaskCounts() {
        Integer count = taskDao.findTaskCounts();
        return count;
    }

    @Override
    @Transactional
    public Result publishTaskOrUpdateTask(SysTask task) {
        Integer integer = 0;
        if (task.getTaskid() == null) {
            //完善任务信息
            int taskType = task.getTktype();

            Integer count = 0;
            if (!redisUtil.hasKey("count")) {
                count = taskDao.findTaskCounts();
                redisUtil.set("count", count);
            } else {
                count = (Integer) redisUtil.get("count");
                count++;
                redisUtil.set("count", count);
            }

            String tkcode = CodeGenerator.Generate(taskType, count);
            task.setTkcode(tkcode);

            //设置任务的状态，默认为1:正常
            task.setStatus(1);

            //获取当前日期时间
            task.setCretim(GetDate.get());

            //设置任务标识，默认为0：正在发布中
            task.setTkflag(0);

            //积分与截止日期设置
            String result = setEndTimeAndIntegral(task);
            assert result != null;
            if (result.equals("截至日期")) {
                return Result.failed("截至日期设置不合理");
            } else if (result.equals("积分不足")) {
                return Result.failed("积分不足");
            }

            //记录发布日志
            TaskPublishLog log = TaskPublishLog.builder()
                    .userid(task.getUserid())
                    .tkcode(task.getTkcode())
                    .cretim(task.getCretim())
                    .build();
            taskDao.logPublish(log);

            //将发布的任务存入数据库
            integer = taskDao.publishTask(task);
        } else {
            int taskType = task.getTktype();
            switch (taskType) {
                case 1:
                    toUrgent(task);
                    break;
                case 0:
                    toPublic(task);
                    break;
                default:
                    break;
            }   //判断是何种任务，并设置前缀

            String result = setEndTimeAndIntegral(task);
            assert result != null;
            if (result.equals("截至日期")) {
                return Result.failed("截至日期设置不合理");
            } else if (result.equals("积分不足")) {
                return Result.failed("积分不足");
            }
            integer = taskDao.updateTask(task);
        }
        //添加任务与任务范围关联
        String tkcode = task.getTkcode();
        //1、首先清空任务与任务范围关联
        taskDao.delTaskAreaRelation(tkcode);
        //2、取任务范围
        List<String> stringList = Arrays.asList(task.getTkarea().split(","));
        //3、添加关联
        taskDao.addTaskAreaRelation(tkcode, stringList);

        return integer > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    private String setEndTimeAndIntegral(SysTask task) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = "成功";
        //判断时间截至时间是否合理
        String endtim = task.getEndtim();
        if (!endtim.equals("")) {
            Date end = null;
            try {
                end = sdf.parse(endtim);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            assert end != null;
            if (end.before(new Date())) {
                s = "截至日期";
                return s;
            }
        } else {
            Date date = new Date();
            long after = date.getTime() + 604800000;
            task.setEndtim(sdf.format(new Date(after)));
        }
        //设置任务积分
        if (task.getIntegr() == null || "".equals(task.getIntegr())) {
            task.setIntegr(5);
        } else {
            int point = task.getIntegr();
            //获取个人的积分，判断个人积分是否足够支持此次任务的发布

            int flag = 10;//取积分

            if (flag < point) {
                s = "积分不足";
                return s;
            }
            task.setIntegr(point + 5);
        }
        return s;
    }


    private void toUrgent(SysTask task) {
        List<SysTask> taskList = taskDao.findTaskCodeByTaskId(task.getTaskid());
        String taskCode = taskList.get(0).getTkcode();
        String code = taskCode.substring(3);
        task.setTkcode("URG" + code);
        task.setTktype(1);
    }

    private void toPublic(SysTask task) {
        List<SysTask> taskList = taskDao.findTaskCodeByTaskId(task.getTaskid());
        String taskCode = taskList.get(0).getTkcode();
        String code = taskCode.substring(3);
        task.setTkcode("PUB" + code);
        task.setTktype(0);
    }

//    @Override
//    public Integer updateTask(Map<String, String> sysTask) {
//        return taskDao.updateTask(sysTask);
//    }

    @Override
    public Integer addTaskType(Map<String, String> taskType) {
        return taskDao.addTaskType(taskType);
    }

    @Override
    public Map findTaskType(String type) {
        Map taskType = new HashMap();
        taskType = taskDao.findTaskType(type);
        return taskType;
    }

    @Override
    public Integer addTaskLevel(Map<String, Object> type) {
        return taskDao.addTaskLevel(type);
    }

    @Override
    public Map findTaskLevel(String type) {
        return taskDao.findTaskLevel(type);
    }

    @Override
    @Transactional
    public Integer updateTaskLevel(Map<String, Object> type) {
        return taskDao.updateTaskLevel(type);
    }

    @Override
    public Integer updateTaskType(Map<String, String> taskType) {
        return taskDao.updateTaskType(taskType);
    }

    @Override
    @Transactional
    public List<SysTask> findTasks(Map<String, Object> conditions) {
        PageUtil.pageParamConver(conditions, true);
        List<SysTask> tasks = taskDao.findTasks(conditions);
        List<SysTask> collect = tasks.stream().map(task -> {
            task.setTareas(taskDao.findRolesTaskAreasTaskCodeId(task.getTkcode()));
            return task;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public TaskType findTaskAreas(Map<String, Object> conditions) {
        return null;
    }

    @Override
    public int findCounts(Map<String, Object> conditions) {
        return taskDao.count(conditions);
    }

    @Override
    public List<TreeNode> findTaskAreaTreeNode(Map<String, Object> params) {
        return taskDao.findTaskAreaTreeNode(params);
    }

    @Override
    public Result delOrRecByTaskId(int taskId) {
        int i = 0;
        //取得当前任务状态
        List<SysTask> taskList = taskDao.findTaskCodeByTaskId(taskId);
        int taskStatus = taskList.get(0).getStatus();
        switch (taskStatus) {
            case 0:
                //恢复的任务状态
                i = taskDao.recByTaskId(taskId);
                break;
            case 1:
                //删除的任务状态
                i = taskDao.delByTaskId(taskId);
                break;
            default:
                break;
        }
        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public PageResult findMyPublishTasks(Map<String, Object> params) {
        PageUtil.pageParamConver(params, true);
        List<SysTask> list = taskDao.findMyPublishTasks(params);
        List<SysTask> collect = list.stream().map(task -> {
            task.setTareas(taskDao.findRolesTaskAreasTaskCodeId(task.getTkcode()));
            return task;
        }).collect(Collectors.toList());
        int count = taskDao.findMyPublishTasksCount(params);
        return PageResult.<SysTask>builder().data(collect).code(0).count((long) count).build();
    }

    @Override
    public PageResult findMyPublishTaskAdopt(Map<String, Object> params) {
        PageUtil.pageParamConver(params, true);
        List<TaskReply> list = taskDao.findMyPublishTaskAdopt(params);
        int count = taskDao.findMyPublishTaskAdoptCount(params);
        return PageResult.<TaskReply>builder().data(list).code(0).count((long) count).build();
    }

    @Override
    public Result adoptReply(Map<String, Object> params) {
        //1、修改回复状态
        int replid = (int) params.get("replid");
        int i = taskDao.adoptReply(replid);

        //2、修改发布者的积分
        int taskid = (int) params.get("taskid");
        List<SysTask> list = taskDao.findTaskByTaskId(taskid);
        String uid = list.get(0).getUserid();
        int integr = list.get(0).getIntegr();
        //积分修改操作

        //3、修改回复者的积分
        int userid = (int) params.get("userid");
        //积分修改操作

        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public Result endTaskByTaskid(Map<String, Integer> params) {
        int taskid = params.get("taskid");
        int i = taskDao.endTaskByTaskid(taskid);
        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public PageResult findTaskComment(Map<String, Object> params) {
        PageUtil.pageParamConver(params, true);
        List<TaskComment> list = taskDao.findTaskComment(params);
        int count = taskDao.findTaskCommentCount(params);
        return PageResult.<TaskComment>builder().data(list).code(0).count((long) count).build();
    }

    @Override
    public Result getTaskByTaskid(Map<String, Object> params) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int taskid = (int) params.get("taskid");
        //判断是否重复接取任务
        int f = taskDao.existGet(params);
        if (f > 0) {
            return Result.failed("不可重复接取任务");
        }
        //判断任务是否过期
        List<SysTask> taskByTaskId = taskDao.findTaskByTaskId(taskid);
        try {
            if (sdf.parse(taskByTaskId.get(0).getEndtim()).before(new Date())) {
                return Result.failed("当前任务已截止");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = taskDao.getTaskByTaskid(params);
        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public PageResult findMyInterceptTasks(Map<String, Object> params) {
        PageUtil.pageParamConver(params, true);
        List<TaskComment> list = taskDao.findMyInterceptTasks(params);
        int count = taskDao.findMyInterceptTasksCount(params);
        return PageResult.<TaskComment>builder().data(list).code(0).count((long) count).build();
    }

    @Override
    public Result onlineReply(Map<String, Object> params) {
        Integer isHave=taskDao.haveOnlineReply(params);
        if (isHave==0){
            int result = taskDao.onlineReply(params);
            return Result.succeed(result == 1 ? "留言成功" : "留言失败");
        }
        return Result.failed("只能留言一次，请在修改界面增加或修改！");
    }

    @Override
    public SysTask findTaskReply(SysTask sysTask) {
        return taskDao.findTaskReply(sysTask);
//        if (sysTask==null{
//        }
    }

    @Override
    public Result updateOnlineReply(Map<String,Object> params) {
        int result = taskDao.updateOnlineReply(params);
        return Result.succeed(result != 0 ? "修改成功" : "修改失败");
    }
}
